<script setup>
import {useRoute,useRouter} from "vue-router";
import CatalogService from "../../stores/CatalogService";

const router = useRouter()
const route = useRoute()
let items = ref([])
let cart = reactive({
      cartItem:[],
      subTotal: 0.0,
    })
const categoryId = route.params.categoryId
const productId = route.params.productId

const getItems = async (cid,pid)=>{
  const [err, res] = await CatalogService.promise_process(CatalogService.getItems(cid,pid));
  if(err){
    console.log(err)
    ElMessage({
      message: '请求服务器失败',
      type: 'error',
    })
  }
  if(res){
   // console.log(res.data)
    items.value = res.data;
    // console.log(items.value)
  }
}

const getItem =  async (itemId)=>{
  const [err, res] =  await CatalogService.promise_process(CatalogService.getItem(itemId))
  if(err){
    console.log(err)
    ElMessage({
      message: '请求服务器失败',
      type: 'error',
    })
  }
  if(res){
    // console.log(res.data)
    let item = res.data
    //console.log(item)
    return item
  }
}

const openAdd = (itemId, num) => {
  ElMessageBox.confirm(
    "确认加入购物车？","提示",
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'success',
    }
  ).then(()=>{
    addToCart(itemId, num)
    ElMessage({
        type: 'success',
        message: '添加成功',
      })
  }).catch(()=>{
    //取消
  }
  )

}

const addToCart = async (itemId, num)=>{
  let item = await getItem(itemId)
  // console.log(item)
  let cItem = {
    item: item,
    quantity: num,
    total: item.listPrice * num,
  }
  console.log(cItem)
  //将item和数量加入到cart中，并计算总价
  cart.cartItem.push(cItem)
  updateCart(cart)
  // router.push({
  //   path:"/cart",
  //   query:{
  //     itemId:itemId,
  //     productId:route.params.productId
  //   }
  // })
}

const updateCart = (cart) =>{
    cart.subTotal = 0
    cart.cartItem.forEach((cItem) =>{
        cart.subTotal += cItem.total
    })
    sessionStorage.setItem('cart', JSON.stringify(cart))
}

const backToProduct = ( ()=>{
  router.push({
    path:`/catalog/`+route.params.categoryId+`/products`,
    params: {
      categoryId:route.params.categoryId
    }
  })
})

onMounted(()=>{

  getItems(categoryId,productId)
  //页面加载周期，从session中获取购物车，并赋给cart，如果session中不存在，存入一个空的cart
  let sessionCart = JSON.parse(sessionStorage.getItem('cart'))
  if(sessionCart != null){
    //console.log(sessionCart)
    cart = sessionCart
  }
  else {
    sessionStorage.setItem('cart', JSON.stringify(cart))
  }
  
   //console.log(cart)
})
</script>

<template>
    <top />
  <div id="Main">
    <div id="BackLink">
      <a @click="backToProduct">Return to Products</a>
    </div>
    <div id="Catalog">

      <h2 style="text-align: center ;padding-top: 80px">{{ itemName }}</h2>
      <el-card>
        <el-table :data="items" style="width: 100%">
          <el-table-column prop="itemId" label="Item ID" align="center"></el-table-column>
          <el-table-column prop="listPrice" label="List Price" align="center"></el-table-column>
          <el-table-column prop="attribute1" label="Attribute" align="center"></el-table-column>
          <el-table-column label=" " align="center">
            <template v-slot="scope">
              <el-button @click="openAdd(scope.row.itemId, 1)">add to cart</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-card>

    </div>
  </div>

    <bottom />
</template>

<style scoped>
#Main{
  /*border: solid red;*/
  padding: 10px;
  width: 80vw;
  height: 75vh;
}
#BackLink{
  position: relative;
  border-top: solid blue;
  border-bottom: solid blue;
  width: 20%;
  height: 50px;
  float: right;
  /*以下3个令文字处于div块正中央，webkit兼容Chrome*/
  display: -webkit-box;
  -webkit-box-align: center;
  -webkit-box-pack: center;
}
el-table{
  position:relative;
  float: bottom;
  border: solid red;
  bottom: 10%;
  margin-top: 1000px;
}
</style>
